package com.eta.gateway.config;

import com.eta.common.constant.HeaderConstant;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import reactor.core.publisher.Mono;

/**
 * @author 星河一叶Ck
 * @date 2025/9/10
 * @description 网关限流配置 => 高并发场景
 */

@Configuration
public class GatewayRateLimitConfig {

    /**
     * 基于用户ID限流 （如果未登录，改用IP限流）
     * @return KeyResolver
     */
    @Bean
    public KeyResolver userKeyResolver() {
        return exchange -> {
            // 从请求头中获取用户ID
            HttpHeaders headers = exchange.getRequest().getHeaders();
            String userId = headers.getFirst(HeaderConstant.X_USER_ID);

            // 如果未登录，用IP作为限流key
            if (userId == null) {
                String ip = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
                return Mono.just(ip);
            }
            return Mono.just(userId);
        };
    }
}
